package com.wanmait.travel.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/code")
public class CodeServlet extends HttpServlet
{
	private Random random =new Random();
	private final String MES ="一二三四五六上下左右前后";
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// TODO 自动生成的方法存根
		response.setContentType("image/jpeg");
		OutputStream out = response.getOutputStream();
		int w=160;
		int h=60;
		BufferedImage bi =new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
		Graphics g =bi.getGraphics();
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, w, h);
		
		
		for(int i=0;i<20;i++) {
			g.setColor(this.getRandomColor());
			g.drawLine(random.nextInt(w),random.nextInt(h), random.nextInt(w),random.nextInt(h));
		}
		
		
		String randCode = this.getRandomString(4);
		request.getSession().setAttribute("randcode", randCode);
		
		for(int i=0;i<randCode.length();i++) {
			int x,y;
			x = i*28+random.nextInt(25);
			y = h-30+random.nextInt(30);
			String ch = randCode.charAt(i)+"";
			g.setColor(this.getRandomColor());
			g.setFont(new Font("黑体",Font.BOLD,25+random.nextInt(10)));
			g.drawString(ch, x, y);
		}
		
		g.setColor(Color.WHITE);
		for(int i=0;i<20;i++) {
			g.drawLine(random.nextInt(w),random.nextInt(h), random.nextInt(w),random.nextInt(h));
		}
		
		ImageIO.write(bi, "jpeg", out);
	}
	private Color getRandomColor() {
		int r = random.nextInt(200);
		int g = random.nextInt(256);
		int b = random.nextInt(256);
		return new Color(r,g,b);
	}
	private String getRandomString(int len) {
		String str = "";
		for(int i=0;i<len;i++) {
			str += (char)('A'+random.nextInt(26));
			//str += MES.charAt(random.nextInt(MES.length()));
		}
		return str;
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO 自动生成的方法存根
		doGet(req,resp);
	}
}
